package com.tushen.labor.data;

import android.os.Handler;
import android.util.Log;

import com.tushen.labor.bean.WeatherInfo;
import com.tushen.labor.util.UIHandler;

import java.util.List;

public class DataManager {

    protected static final String TAG = "DataManager";

    private static DataManager mInstance = null;

    private Thread mDataThread = null;

    private DataListener.WeatherListener weatherListener;

    private Handler handler;

    private boolean mRunning = false;

    private DataManager() {

    }


    public static DataManager getInstance() {
        if (mInstance == null) {
            synchronized (DataManager.class) {
                if (mInstance == null) {
                    mInstance = new DataManager();
                }
            }
        }
        return mInstance;
    }

    public void start() {
        stop();
        mRunning = true;
        mDataThread = new Thread(new DataTask());
        mDataThread.start();
    }

    public void stop() {
        mRunning = false;
        try {
            if (mDataThread != null) {
                mDataThread.interrupt();
                mDataThread.join(1000);
            }
        } catch (Exception e) {

        }
        mDataThread = null;
    }


    public void setHandler(Handler h) {
        this.handler = h;
    }

    public void setWeatherListener(DataListener.WeatherListener weatherListener) {
        this.weatherListener = weatherListener;
    }

    private class DataTask implements Runnable {
        @Override
        public void run() {
            Log.d(TAG, "DataTask start...");

            while (mRunning) {

                try {
                    //天气一小时更新一次
                    getWeatherInfo();

                    Thread.sleep(1000*60*30);
                } catch (InterruptedException e) {
                    Log.d(TAG, "DataTask catch InterruptedException..break..");
                    break;
                } catch (Exception e) {
                    Log.e(TAG, "DataTask catch Exception e = " + e.getClass().getSimpleName());
                    e.printStackTrace();
                }
            }
            Log.d(TAG, "DataTask end...");
        }
    }

    private boolean getWeatherInfo() {
        try {

            if(weatherListener == null)
                return false;

            final List<WeatherInfo> list = DataUtil.getWeatherInfo();
            if(list == null || list.isEmpty()){
                return false;
            }

            UIHandler.getInstance().post(handler, new Runnable() {
                @Override
                public void run() {
                    weatherListener.onDataChanged(list);
                }
            });

            return true;
        } catch (Exception e) {
            Log.e(TAG, "getWeatherInfo catch Exception e = " + e.getClass().getSimpleName());
            e.printStackTrace();
        }
        return false;
    }

}
